#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log
from sqlalchemy.orm import mapper, sessionmaker
from datetime import datetime
from sqlalchemy import Table, MetaData, Column, ForeignKey, Integer, BigInteger, String, Unicode, UnicodeText, DateTime, \
    desc
from controls.data_pool_mysql import engine

metadata = MetaData()
Session = sessionmaker()  # 创建了一个自定义了的 Session类
Session.configure(bind=engine)  # 将创建的数据库连接关联到这个session

"""city_map collection has 
    id:                自增id (int)
    cityid:            城市id (int)
    version:           地图版本号 (int)
    csbfile:           csbfile(string)  group/file
    jpgfile:           jpgfile(string)
    pngfile:           pngfile(string)
    plistfile:         plistfile(string)
    iconfile:          城市小球图标(string)
    jsonfile:          城市所有景点jsonfile(string)  group/file
    ctime:             添加时间(datetime)
"""


class CityMapItem(object):  # 创建一个映射类

    def to_dict(self):
        res = {}
        res['id'] = self.id
        res['cityid'] = self.cityid
        res['version'] = int(self.version)
        res['csbfile'] = self.csbfile
        res['jpgfile'] = self.jpgfile
        res['pngfile'] = self.pngfile
        res['plistfile'] = self.plistfile
        res['iconfile'] = self.iconfile
        res['jsonfile'] = self.jsonfile
        res['ctime'] = self.ctime.strftime("%Y-%m-%d %H:%M:%S") if self.ctime else ''
        return res

    def __repr__(self):
        return "cityid : %d, version: %d" % (self.cityid, self.version)


city_map_table = Table(
    'city_map', metadata,
    Column('id', Integer, primary_key=True),
    Column('cityid', Integer, nullable=False),
    Column('version', Integer, nullable=False),
    Column('csbfile', Unicode(150), nullable=False),
    Column('jpgfile', Unicode(150), nullable=False),
    Column('pngfile', Unicode(150), nullable=False),
    Column('plistfile', Unicode(150), nullable=False),
    Column('iconfile', Unicode(150), default='', nullable=False),
    Column('jsonfile', Unicode(150), nullable=False),
    Column('ctime', DateTime, default=datetime.now, nullable=False)
)

mapper(CityMapItem, city_map_table)  # 把表映射到类


def create_city_map_table_if_not_exist():
    metadata.create_all(engine)  # 在数据库中生成表


def add_city_map_item(p_item):
    create_city_map_table_if_not_exist()
    item = CityMapItem()
    item.cityid = p_item['cityid']
    item.version = p_item['version']
    item.csbfile = p_item['csbfile']
    item.jpgfile = p_item['jpgfile']
    item.pngfile = p_item['pngfile']
    item.plistfile = p_item['plistfile']
    item.iconfile = p_item['iconfile']
    item.jsonfile = p_item['jsonfile']
    item.ctime = p_item['ctime']

    try:
        session = Session()
        session.add(item)  # 往session中添加内容
        session.flush()  # 保存数据
        session.commit()  # 数据库事务的提交,sisson自动过期而不需要关闭
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()


'''
get the newest citymap by cityid
'''


def get_city_map_by_cityid(p_cityid):
    try:
        session = Session()
        item = session.query(CityMapItem).filter_by(cityid=p_cityid).order_by(desc(CityMapItem.version)).first()
        if not item:
            return None
        return item.to_dict()
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


'''
get the citymap by cityid and version
'''


def get_city_map_by_cityid_ver(p_cityid, p_version):
    try:
        session = Session()
        item = session.query(CityMapItem).filter_by(cityid=p_cityid, version=p_version).first()
        if not item:
            return None
        return item.to_dict()
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()


'''
get all published citie's icon, just highest version(>0). 
unpublished cities wont be return(version or versioninfo is 0, mean this city is unpublished)
'''


def get_city_icon_all():
    try:
        session = Session()
        items = session.query(CityMapItem).filter(CityMapItem.version > 0).all()
        res = {}
        for item in items:
            if not res.has_key(item.cityid):
                res[item.cityid] = {}
            res[item.cityid][item.version] = item.iconfile
        return res
    except Exception, e:
        log.exp(e)
        return None
    finally:
        session.close()


if __name__ == "__main__":
    create_city_map_table_if_not_exist()
    # item1 = {'imgid':1234,'group':1,'path':'M00/00/00/0g6asVUlhsGAH4NTAAfYzBjHljI331','ext':'jpg'}
    # add_city_map_item( item1 )
